package com.htg.tdtwebapi;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

public class TdtWebApi {

    protected String key;

    private TdtWebApi() throws Exception {
        throw new Exception("这个构造方法不让用");
    }

    public TdtWebApi(String key) {
        this.key = key;
    }

    protected boolean isParamLegal(String param) {
        if (param == null | param.isEmpty()) return false;
        return true;
    }

    protected boolean isParamsLegal(String... params) {
        for (int i = 0; i < params.length; i++) {
            String param = params[i];
            boolean legal = isParamLegal(param);
            if (legal) {

            } else {
                return false;
            }
        }
        return true;
    }

    protected String get(String url, Map<String, Object> params) throws Exception {
        //
        String temp = url + "?";
        //
        StringBuilder stringBuilder = new StringBuilder();
        Iterator<String> iteratorKey = params.keySet().iterator();
        while (iteratorKey.hasNext()) {
            String key = iteratorKey.next();
            Object value = params.get(key);
            stringBuilder.append(key);
            stringBuilder.append("=");
            stringBuilder.append(value);
            stringBuilder.append("&");
        }
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        //
        temp += stringBuilder.toString();
        //
        Log.i("lala"," url : "+temp);
        URL u = new URL(temp);
        HttpURLConnection httpURLConnection = (HttpURLConnection) u.openConnection();
        httpURLConnection.setRequestMethod("GET");
        int code = httpURLConnection.getResponseCode();
        if (code == 200) {
            InputStream inputStream = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            return stringBuffer.toString();
        } else {
            String msg = httpURLConnection.getResponseMessage();
            throw new Exception("请求异常 ： " + msg);
        }
    }

}
